<script setup>
import { reactive, ref } from 'vue'
import { resetUserPassword } from '@/api/system'

const registerForm = ref()

const registerParams = reactive({
  telephone: null,
  oldPassword: null,
  newPassword: null
})

const customRules = reactive({
  telephone: {
    rules: [{ required: true, errorMessage: '手机号不能为空' }]
  },
  oldPassword: {
    rules: [{ required: true, errorMessage: '旧密码不能为空' }]
  },
  newPassword: {
    rules: [{ required: true, errorMessage: '新密码不能为空' }]
  }
})

const handleUpdatePassword = async () => {
  registerForm.value
    .validate()
    .then(async ({ oldPassword, newPassword }) => {
      if (oldPassword === newPassword) {
        return uni.showModal({ title: '提示', content: '新密码与旧密码不能相同' })
      }

      const { code, msg } = await resetUserPassword(registerParams)
      if (code === 200) {
        uni.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.removeStorageSync('accessToken')
              uni.reLaunch({
                url: '/pages/login/index'
              })
            }
          }
        })
        return
      }

      uni.showModal({ title: '提示', content: msg })
    })
    .catch((err) => {
      console.log('err', err)
    })
}
</script>
<template>
  <view class="example">
    <uni-forms
      label-position="top"
      :modelValue="registerParams"
      :rules="customRules"
      ref="registerForm"
    >
      <uni-forms-item label="手机号" required name="telephone">
        <uni-easyinput placeholder="请输入手机号" v-model="registerParams.telephone" />
      </uni-forms-item>
      <uni-forms-item label="旧密码" required name="oldPassword">
        <uni-easyinput
          placeholder="请输入旧密码"
          v-model="registerParams.oldPassword"
          type="password"
        />
      </uni-forms-item>
      <uni-forms-item label="新密码" required name="newPassword">
        <uni-easyinput
          placeholder="请输入新密码"
          v-model="registerParams.newPassword"
          type="password"
        />
      </uni-forms-item>
    </uni-forms>
    <button type="primary" @click="handleUpdatePassword">立即修改</button>
  </view>
</template>

<style lang="scss" scoped>
.example {
  padding: 15px;
  background-color: #fff;
}
</style>
